
#include <Windows.h>
#include <iostream>
#include <cstdio>

extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

using namespace std;

extern "C"
{
void ReportError(lua_State* state, int status)
{
    if(status != 0)
    {
        cerr << lua_tostring(state, -1);
    }
}

static int HostPrint(lua_State* L)
{
    char const* text = lua_tostring(L, 1);
    cout << text << endl;
    return 0;
}
}

int main(int arcCnt, char** argv)
{
    Sleep(1000);

    const static struct luaL_reg misc[] = 
    {
        {"Print", &HostPrint},
        {0, 0}
    };

    char fuckyou[256];
    try
    {


        int result = 0;

        lua_State* state = lua_open();
        luaL_openlibs(state);

        //lua_register(state, "HostPrint", HostPrint);

        if(luaL_loadfile(state, "export.lua") || lua_pcall(state, 0, 0, 0))
        {
            cout << "load load file failed" << endl;
            cout << lua_tostring(state, -1); // if lua crashes comment this line

            getchar();
            return -1;
        }

        if(result != 0) ReportError(state, result);



        lua_getglobal(state, "LuaExportStart");
        if(lua_pcall(state, 0, 0, 0) != 0)
        {
            cout << "lua export start failed" << endl;
            cout << lua_tostring(state, -1);//if lua crashes comment this line
            getchar();
        }

        while(true)
        {
            cout << "loop" << endl;

            //call beforeNextFrame
            lua_getglobal(state, "LuaExportBeforeNextFrame");
            if(!lua_isfunction(state, -1))
            {
                cout << "Export before next frame failed because stack element was no function" << endl;
            }

            if(lua_pcall(state, 0, 0, 0) != 0)
            {
                cout << lua_tostring(state, -1) << endl; //if lua crashes comment this line
            }


            //call export activity 
            lua_getglobal(state, "LuaExportActivityNextEvent");
            if(!lua_isfunction(state, -1))
            {
                cout << "Export activity failed because stack element was no function" << endl;
            }

            lua_pushnumber(state, 1);

            if(lua_pcall(state, 1, 1, 0) != 0)
            {
                cout << lua_tostring(state, -1) << endl; // if lua crashes comment this line
            }
            float value = lua_tonumber(state, -1);
            
            lua_pop(state, 1);

            Sleep(1000);

            //getchar();
        }

        cout << "Program abort.... Press key to finish";
        getchar();
    }
    catch(...)
    {
        cout << "Exception... Press key to finish" << endl;
        getchar();
    }
}